import os
import requests
from common import write_to_file
from common import create_token
from common import create_authorization
from common import factory_connection
from common import close_connection
from common import get_fcodebyorder
from datetime import datetime


home_dir = os.path.expanduser("~")
file_path = os.path.join(home_dir, 'Downloads', 'file.tsv')
token = create_token()
sql_list = ['colorful','newlook','elegant','fruit','wf','pn','peach','meow','lion']



def del_shipment(factory_code,order_no):
    print(f"{factory_code}\t{order_no}")
    
    connection = factory_connection(factory_code)
    cursor = connection.cursor()
    cursor.execute(f'SELECT id FROM opr_shipment WHERE ch_shipment_no = "{order_no}" and `status` != "8" and flag & 512 != 512')
    result = cursor.fetchone()
    if result:
        shipment_id = result[0]
        cursor.execute(f'update opr_shipment set flag = 512 WHERE id = {shipment_id}  and flag & 512 != 512')
        cursor.execute(f'update sta_shipment set flag = 512 WHERE shipment_id = {shipment_id}  and flag & 512 != 512')
        connection.commit()
    close_connection(connection)


def get_shipment(factory_code,order_no):
    connection = factory_connection(factory_code)
    cursor = connection.cursor()
    cursor.execute(f'SELECT ch_shipment_no FROM opr_shipment WHERE order_no = "{order_no}" and `status` != "8" and flag & 512 != 512')
    results = cursor.fetchall()
    if results:
        for row in results:
            shipment_nos = row
            shipment_no = shipment_nos[0]
            if shipment_no:
                write_to_file("~/Downloads/shipment_no.csv",factory_code,shipment_no)
    close_connection(connection)




def skip_pack(factory_code,order_no):
    current_time = datetime.now()
    formatted_time = current_time.strftime("%Y-%m-%d %H:%M:%S")
    connection = factory_connection(factory_code)
    cursor = connection.cursor()
    cursor.execute(f'select id from opr_shipment where order_no = "{order_no}"')
    results = cursor.fetchall()
    for row in results:
        shipment_ids = row
        shipment_id = shipment_ids[0]
        cursor.execute(f'select id,status from opr_product where shipment_id = {shipment_id} and flag & 512 != 512')
        b_results = cursor.fetchall()
        for row in b_results:
            ids = row
            id = ids[0]
            status = ids[1]
            if status == '7':
                cursor.execute(f"UPDATE opr_product set status = '9' where id = {id}")
                cursor.execute(
                    f"INSERT INTO sta_product "
                    f"(`product_id`, `status`, `user_id`, `create_at`, `create_by`, `modify_at`, `modify_by`, `flag`)"
                    f" VALUES "
                    f"({id}, '8', 46, '{formatted_time}', '大鲸洗-谢恩情', '{formatted_time}', '大鲸洗-谢恩情', 1),"
                    f"({id}, '9', 46, '{formatted_time}', '大鲸洗-谢恩情', '{formatted_time}', '大鲸洗-谢恩情', 1);"
                )
                cursor.execute(
                    f"INSERT INTO post_pack "
                    f"(`product_id`, `user_id`, `create_at`, `create_by`, `modify_at`, `modify_by`, `flag`)"
                    f" VALUES "
                    f"({id}, 46, '{formatted_time}', '大鲸洗-谢恩情', '{formatted_time}', '大鲸洗-谢恩情', 1);"
                )
                connection.commit()
        cursor.execute(f"UPDATE opr_shipment set status = '2' where id = {shipment_id}")
        cursor.execute(
            f"INSERT INTO sta_shipment "
            f"(`shipment_id`, `status`, `user_id`, `create_at`, `create_by`, `modify_at`, `modify_by`, `flag`)"
            f" VALUES "
            f"({shipment_id}, '2', 46, '{formatted_time}', '大鲸洗-谢恩情', '{formatted_time}', '大鲸洗-谢恩情', 1);"
        )
        connection.commit()
    close_connection(connection)





def out_data(factory_code,order_no):
    current_time = datetime.now()
    formatted_time = current_time.strftime("%Y-%m-%d %H:%M:%S")
    connection = factory_connection(factory_code)
    cursor = connection.cursor()
    cursor.execute(f'select id from opr_shipment where ch_shipment_no = "{order_no}" and flag & 512 != 512')
    results = cursor.fetchone()
    shipment_id = results[0]
    cursor.execute(f"UPDATE opr_shipment set status = '8' where id = {shipment_id}")
    cursor.execute(
        f"INSERT INTO sta_shipment "
        f"(`shipment_id`, `status`, `user_id`, `create_at`, `create_by`, `modify_at`, `modify_by`, `flag`)"
        f" VALUES " 
        f"({shipment_id}, '8', 46, '{formatted_time}', '大鲸洗-谢恩情', '{formatted_time}', '大鲸洗-谢恩情', 1);"
    )
    connection.commit()
    cursor.execute(f'select id from opr_product where shipment_id = "{shipment_id} and flag & 512 != 512"')
    b_results = cursor.fetchall()
    for row in b_results:
        product_id = row[0]
        cursor.execute(f"UPDATE opr_product set status = '13' where id = {product_id}")
        cursor.execute(
            f"INSERT INTO sta_product "
            f"(`product_id`, `status`, `user_id`, `create_at`, `create_by`, `modify_at`, `modify_by`, `flag`)"
            f" VALUES "
            f"({product_id}, '13', 46, '{formatted_time}', '大鲸洗-谢恩情', '{formatted_time}', '大鲸洗-谢恩情', 1);"
        )
        connection.commit()
    close_connection(connection)








def channel_request(factory_code, order_no):
    connection = factory_connection(factory_code)

    cursor = connection.cursor()

    cursor.execute(f'select pu.ch_pickup_no, ca.ak, ca.sk from opr_pickup pu join sys_channel_auth ca on ca.channel_id = pu.channel_id where pu.order_no = "{order_no}"')
    #cursor.execute(f'select pu.ch_pickup_no, ca.ak, ca.sk from opr_pickup pu join sys_channel_auth ca on ca.channel_id = pu.channel_id where pu.ch_pickup_no = "{order_no}"')

    results = cursor.fetchall()
    for result in results:
        ch_pickup_no, ak, sk = result
        print(f"ch_pickup_no: {ch_pickup_no}, ak: {ak}, sk: {sk}")
        url = f"/api/channel/pickup/{ch_pickup_no}"
        URL = f"https://{factory_code}.haishenxiyi.net{url}"
        header = create_authorization("DELETE",url,ak, sk)
        #header = create_authorization("PUT",url,ak, sk)
        headers = {
            'Authorization': header,
            'Content-Type': 'application/json'
        }
        print(URL)
        print(headers)
        response = requests.delete(URL,headers=headers)
        #response = requests.put(URL,headers=headers)
        print("Status Code:", response.status_code)
        print("Response Text:", response.text)
    close_connection(connection)

with open(file_path, 'r') as file:
    lines = file.readlines()

for line in lines:
    #splited = line.split(" ")
    splited = line.split("\t")
    if len(splited) <= 1:
        order_no = splited[0].strip()
        fcode = None
    else:
        fcode = splited[0].strip()
        order_no = splited[1].strip()

       
    if not fcode:
        for item in sql_list:
            print(item)
            fcode = get_fcodebyorder(order_no,item)
            if fcode:
                break
            else:
                print("未找到 工厂代码")
    if not fcode:
         print('fcode为空')
         continue
    #get_shipment(fcode,order_no)
    #删除入厂单
    channel_request(fcode,order_no)
    #删除出厂单
    #del_shipment(fcode,order_no)
    #out_data(fcode,order_no)